#include "WeiBo.h"

CWeiBo *CWeiBo::WeiboInstance = NULL;

CWeiBo::CWeiBo()
{
    //Init();
}

CWeiBo::~CWeiBo()
{

}

bool CWeiBo::Init()
{
    Py_Initialize();
    if (!Py_IsInitialized())
        return false;
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    pModule = PyImport_ImportModule("SmartWeibo");
    if (!pModule) {
        cout << "Cant open python file!" << endl;
        return false;
    }
    pyDict = PyModule_GetDict(pModule);
    if (!pyDict) {
        cout << "Cant find dictionary." << endl;
        return false;
    }

    pyWeiboClass = PyDict_GetItemString(pyDict, "SmartWeibo");
    if (!pyWeiboClass) {
        cout << "Cant find second class." << endl;
        return false;
    }

    pyInstance = PyInstance_New(pyWeiboClass, NULL, NULL);
    if (!pyInstance) {
        cout << "Cant create second instance." << endl;
        return false;
    }

    PyObject_CallMethod(pyInstance, "init", NULL);


    return true;
}

CWeiBo *CWeiBo::GetWeiboInstance()
{
    if(WeiboInstance == NULL)
        WeiboInstance = new CWeiBo;

    return WeiboInstance;
}

void CWeiBo::PostStatus(char *status)
{
    PyObject_CallMethod(pyInstance, "PostStatus", "s", status);
}

void CWeiBo::GetMostRecentStatus(char *retStatus)
{
    PyObject *retValue = PyObject_CallMethod(pyInstance, "GetMostRecentStatus", NULL);
    if(retValue == NULL){
        cerr << "Get no return value" << endl;
    }
    PyArg_Parse(retValue, "s", &retStatus);
}

void CWeiBo::GetRecentStatus(char *retStatus)
{
    PyObject_CallMethod(pyInstance,"UpdateCache", NULL);
    PyObject *retValue = PyObject_CallMethod(pyInstance, "GetNRecentStatus", "i", 0);
    PyArg_Parse(retValue, "s", &retStatus);
    cout << retStatus << endl;
    retValue = PyObject_CallMethod(pyInstance, "GetNRecentStatus", "i", 0);
    if(retValue == NULL){
        cerr << "Get no return value" << endl;
    }
    PyArg_Parse(retValue, "s", &retStatus);
    cout << retStatus << endl;
}

void CWeiBo::Cleanup()
{
    //释放
    Py_DECREF(pyInstance);
    Py_DECREF(pyWeiboClass);
    Py_DECREF(pModule);
    Py_Finalize();

    if(WeiboInstance)
    {
        delete WeiboInstance;
        WeiboInstance = 0;
    }
}

